<?php

namespace App\Http\Controllers\Api\V1;

use App\Game\Game;
use App\Http\Resources\OddsHandicapCollection;
use App\Http\Resources\PlatCollection;
use App\Http\Resources\QuotaHandicapCollection;
use App\Models\Def\MainGamePlat;
use App\Models\GameList;
use App\Models\Conf\Site;
use App\Models\OddsHandicap;
use App\Models\OddType;
use App\Models\QuotaHandicap;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Models\Log\PlayerBetFlow;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\GameListCollection;
use App\Http\Controllers\AppBaseController;
use App\Http\Resources\PlayerBetFlowCollection;
use App\Http\Resources\Game as GameResource;

class GameController extends AppBaseController
{
    use Helpers;

    public $game;
    public $cUserMaxLen;
    public $userMaxLen;

    public function __construct()
    {
        if (app()->environment() == 'product') {
            $this->middleware(['api.auth', 'game.api.check']);
        }
        if (!empty(request('mainGamePlat'))) {
            $this->game = new Game(request('mainGamePlat'));
            $this->cUserMaxLen = $this->game->getPlatLength();
            $this->userMaxLen = $this->game->plat->getLength();
        }

    }

    /**
     * gameapi
     * 2018/9/7 23:22
     * Administrator
     * createMember
     * 创建帐号
     * @param Request $request
     * @return mixed
     */
    public function createMember(Request $request)
    {
        $this->valid($request, [
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'musername' => 'required|min:4|max:' . $this->cUserMaxLen . '|string',
                'username' => 'required|min:3|max:20|string',
                'oddType' => 'nullable|integer|exists:odd_types,id',
            ]
        );
    \Log::info('请入创建用户方法');
        $output = $this->game->createMember($request);
        return $this->gameResponse($output);
    }


    /**
     * gameapi
     * 2018/9/7 23:22
     * Administrator
     * getBalance
     * 获取余额
     * @param Request $request
     * @return mixed
     */
    public function getBalance(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
            ]
        );

        $output = $this->game->getBalance($request);
        return $this->gameResponse($output);

    }

    /**
     * gameapi
     * 2018/9/7 23:47
     * Administrator
     * transferIn
     * 转入游戏
     * @param Request $request
     * @return mixed
     */
    public function transferIn(Request $request)
    {
        $this->valid($request, [
            'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
            'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
            'price' => 'required|numeric|min:1',
        ],
            [
                'price.min' => '金额最小大于等于1元'
            ]
        );

        $output = $this->game->transferIn($request);
        return $this->gameResponse($output);


    }

    /**
     * gameapi
     * 2018/9/7 23:47
     * Administrator
     * transferTo
     * 转出游戏
     * @param Request $request
     * @return mixed
     */
    public function transferTo(Request $request)
    {
        $this->valid($request, [
            'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
            'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
            'price' => 'required|numeric|min:1',
        ],
            [
                'price.min' => '金额最小大于等于1元'
            ]
        );

        $output = $this->game->transferTo($request);
        return $this->gameResponse($output);

    }

    /**
     * gameapi
     * 2018/9/7 23:47
     * Administrator
     * checkTransfer
     * 检查订单
     * @param Request $request
     * @return mixed
     */
    public function checkTransfer(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
                'transferid' => 'required|string',
            ]
        );

        $output = $this->game->checkTransfer($request);
        return $this->gameResponse($output);

    }

    /**
     * gameapi
     * 2018/9/7 23:48
     * Administrator
     * kick
     * 踢线
     * @param Request $request
     * @return mixed
     */
    public function kick(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
            ]
        );

        $output = $this->game->kick($request);
        return $this->gameResponse($output);
    }

    /**
     * gameapi
     * 2018/9/25 19:14
     * Administrator
     * lottoCode
     * 彩票类平台获取彩种
     * @param Request $request
     * @return mixed
     */
    public function lotteryCode(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            ]
        );

        $output = $this->game->lotteryCode($request);
        return $this->gameResponse($output);
    }

    /**
     * gameapi
     * 2018/9/7 23:48
     * Administrator
     * joinGame
     * 进入游戏
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function joinGame(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
                'password' => 'required|string',
                'gamecode' => 'required|string',
                'demo' => 'required|string',
                'is_lobby' => 'nullable|in:0,1',
                'odds_handicap' => 'nullable|string|exists:odds_handicaps,code',
                'quota_handicap' => 'nullable|string|exists:quota_handicaps,code',
                'ip' => 'nullable|ipv4',
            ]
        );

        $output = $this->game->joinGame($request);

        if (!$output['success']) {
            return $this->response->array([
                    'status_code' => 500,
                    'message' => $output['message'],
                    'data' => ''
                ]
            );
        } else {
            if (isset($output['data']['url'])) {
                if (app()->environment() == 'test') {
                    dd($output['data']['url']);
                }
                return redirect()->to($output['data']['url']);
            } else {
                return view('pt', $output['data']);
            }
        }


    }

    /**
     * gameapi
     * 2018/9/7 23:48
     * Administrator
     * joinMobileGame
     * 进入游戏（手机端）
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function joinMobileGame(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
                'accountUserName' => 'required|min:4|max:' . $this->userMaxLen . '|string|exists:inf_site_players,username',
                'password' => 'required|string',
                'gamecode' => 'required|string',
                'demo' => 'required|string',
                'is_lobby' => 'nullable|in:0,1',
                'odds_handicap' => 'nullable|string|exists:odds_handicaps,code',
                'quota_handicap' => 'nullable|string|exists:quota_handicaps,code',
                'ip' => 'nullable|ipv4',
            ]
        );

        $output = $this->game->joinMobileGame($request);

        if (!$output['success']) {
            return $this->response->array([
                    'status_code' => 500,
                    'message' => $output['message'],
                    'data' => ''
                ]
            );
        } else {
            if (isset($output['data']['url'])) {
                if (app()->environment() == 'test') {
                    dd($output['data']['url']);
                }
                return redirect()->to($output['data']['url']);
            } else {
                return view('pth5', $output['data']);
            }
        }
    }

    /**
     * gameapi_new
     * 2018/12/18 19:21
     * Administrator
     * getRecord
     * 获取游戏记录
     * @param Request $request
     * @return mixed
     */
    public function getRecord(Request $request)
    {
        $this->valid($request, [
                'startTime' => 'required|date',
                'endTime' => 'required|date',
                'username' => 'required',
            ]
        );

        $per_page = $request->per_page ?? 500;
        $per_page = $per_page <= 500 ? $per_page : 1000;
        $startTime = $request->input('startTime', '');
        $endTime = $request->input('endTime', '');
        $username = $request->input('username', '');
        if (empty($startTime) || empty($endTime)) {
            $time = time();
            $startTime = date('Y-m-d H:i:s', $time - 300);
            $endTime = date('Y-m-d H:i:s', $time);
        }

        $username=is_array($username)?$username:[$username];

        $playerBetFlow = PlayerBetFlow::where([
            ['updated_at','>=', $startTime],
            ['updated_at','<=', $endTime],
        ])->whereIn('site_username',$username);

        $playerBetFlows = $playerBetFlow->paginate((int)$per_page);

        $playerBetFlows->appends([
                'startTime' => $request->startTime,
                'endTime' => $request->endTime,
                'username' => $request->username,
            ]
        )->render();
//$aaa = new PlayerBetFlowCollection($playerBetFlows);
//        file_put_contents('/home/gameapi/storage/logs/test.log', 'aaaaa...'.PHP_EOL, FILE_APPEND);
//        file_put_contents('/home/gameapi/storage/logs/test.log', 'ccc...'.json_encode($aaa).PHP_EOL, FILE_APPEND);
        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new PlayerBetFlowCollection($playerBetFlows)
                ]
            );

    }

    /**
     * gameapi
     * 2018/10/21 23:08
     * Administrator
     * gameList
     * 获取平台游戏列表
     * @param Request $request
     * @return mixed
     */
    public function gameList(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            ]
        );

        $main_game_plat_code = $request->only(['mainGamePlat']);
        $gameLists = GameList::status()->where('main_game_plat_code', $main_game_plat_code)->paginate(2000);

        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new GameListCollection($gameLists)
                ]
            );
    }

    /**
     * gameapi
     * 2018/10/31 18:21
     * Administrator
     * gameInfo
     *
     * @param Request $request
     * @return mixed
     */
    public function gameInfo(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'unique_key' => 'required|string|exists:game_lists,unique_key',
            ]
        );

        $unique_key = $request->only(['unique_key']);
        $game = GameList::status()->where('unique_key', $unique_key)->first();

        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new GameResource($game)
                ]
            );
    }

    /**
     * gameapi
     * 2018/10/30 17:19
     * Administrator
     * oddType
     * 获取赔率盘口列表
     * @param Request $request
     * @return mixed
     */
    public function oddsHandicap(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            ]
        );

        $mainGamePlat = MainGamePlat::where('main_game_plat_code', $request->mainGamePlat)->first();
        $oddsHandicaps = OddsHandicap::where('plat_id', (integer)$mainGamePlat->id)->paginate(2000);

        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new OddsHandicapCollection($oddsHandicaps)
                ]
            );
    }

    /**
     * gameapi
     * 2018/10/30 17:19
     * Administrator
     * quotaHandicap
     * 获取赔率盘口列表
     * @param Request $request
     * @return mixed
     */
    public function quotaHandicap(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
                'mainGamePlat' => 'required|string|exists:def_main_game_plats,main_game_plat_code',
            ]
        );

        $mainGamePlat = MainGamePlat::where('main_game_plat_code', $request->mainGamePlat)->first();
        $quotaHandicaps = QuotaHandicap::where('plat_id', $mainGamePlat->id)->paginate(2000);

        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new QuotaHandicapCollection($quotaHandicaps)
                ]
            );
    }

    /**
     * gameapi
     * 2018/11/11 16:53
     * Administrator
     * platList
     * 平台列表
     * @param Request $request
     * @return mixed
     */
    public function platList(Request $request)
    {
        $this->valid($request, [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
            ]
        );
        $site = Site::where('username', $request->username)->first();
        $plats = $site->MainGamePlat()->paginate(2000);

        return $this->response
            ->array([
                    'status_code' => 200,
                    'message' => '',
                    'data' => new PlatCollection($plats)
                ]
            );

    }


    /**
     * gameapi
     * 2018/9/7 22:55
     * Administrator
     * valid
     * 表单验证
     * @param Request $request
     * @param array $rule
     * @return bool|void
     */
    protected function valid(Request $request, array $rule, array $message = [])
    {
        $valid = Validator::make($request->all(), $rule, $message);
        if ($valid->fails()) {
            return $this->response->error(json_encode($valid->errors(), JSON_UNESCAPED_UNICODE), 400);
        } else {
            return true;
        }
    }

    /**
     * gameapi
     * 2018/9/10 21:18
     * Administrator
     * gameResponse
     * @param $output
     * @return mixed
     */
    public function gameResponse($output)
    {
        if (array_key_exists('success', $output)) {
            if ($output['success']) {
                return $this->response->array([
                        'status_code' => 200,
                        'message' => $output['message'],
                        'data' => $output['data'],
                    ]
                );
            } else {
                return $this->response->array([
                        'status_code' => 500,
                        'message' => $output['message'],
                        'data' => $output['data'],
                    ]
                );

            }

        } else {
            return $this->response->error('没有返回结果', 500);
        }
    }

    /**
     * gameapi
     * 2018/11/3 19:12
     * Administrator
     * __call
     *
     * @param string $name
     * @param array $arguments
     * @return mixed|void
     */
    public function __call($name, $arguments)
    {
        $this->valid(request(), [
                'username' => 'required|min:3|max:20|string|exists:conf_sites,username',
            ]
        );

        if (method_exists($this->game->plat, $name)) {
            $result = $this->game->plat->$name();
            return $this->gameResponse($result);
        } else {
            return $this->response->error('请求函数在平台中不存在', 500);
        }
    }


}
